package com.xplay.xpocker.socket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * @author wanjie
 * @date 2021/3/17 14:44
 */

public class HeartBeatHandler extends IdleStateHandler {



    private static final int READ_IDLE_TIME = 30; // 读空闲时间，单位：秒
    private static final int WRITE_IDLE_TIME = 3; // 写空闲时间，单位：秒
    private static final int ALL_IDLE_TIME = 3; // 读写都空闲的时间，单位：秒

    public HeartBeatHandler() {
        super(READ_IDLE_TIME, WRITE_IDLE_TIME, ALL_IDLE_TIME);
    }

    int readIdleTimes = 0;


    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        IdleStateEvent event = (IdleStateEvent)evt;

        String eventType = null;
        switch (event.state()){
            case READER_IDLE:
                eventType = "读空闲";
                //readIdleTimes ++; // 读空闲的计数加1
                break;
            case WRITER_IDLE:
                eventType = "写空闲";
                // 不处理
                break;
            case ALL_IDLE:
                eventType ="读写空闲";
                // 不处理
                break;
        }
        System.out.println(ctx.channel().remoteAddress() + "超时事件：" +eventType);
        ctx.channel().writeAndFlush("you are out");
        ctx.channel().close();
    }
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.err.println("=== " + ctx.channel().remoteAddress() + " is active ===");
    }

}

